package com.ubxtech.web.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.ubxtech.core.context.ContextConstants;
import com.ubxtech.core.enums.UserAgentSystemEnum;
import org.springframework.http.HttpStatus;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;

/**
 * @author Victor.Xiao
 * @since 2022-01-17 14:18
 **/
public class WebUtil {

    public static String getHeader(HttpServletRequest request, String name) {
        String value = request.getHeader(name);
        if (StrUtil.isEmpty(value)) {
            return "";
        }
        return URLUtil.decode(value);
    }


    public static HttpStatus resolveCode(Integer code) {
        if (code >= 600) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        for (HttpStatus value : HttpStatus.values()) {
            if (value.value() == code) {
                return value;
            }
        }
        return HttpStatus.INTERNAL_SERVER_ERROR;
    }

    /**
     * 判断哪种类型的客户端,方便支持多客户端登录
     * @author Victor.Xiao
     * @since 2023-12-25 15:51
     * @return com.ubxtech.core.enums.UserAgentSystemEnum
    */
    public static UserAgentSystemEnum getUserAgentType() {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return UserAgentSystemEnum.PC;
        }
        HttpServletRequest request = attributes.getRequest();
        String value = request.getHeader(ContextConstants.HEADER_USER_AGENT);

        if (StrUtil.isEmpty(value)) {
            return UserAgentSystemEnum.PC;
        }
        value = value.toLowerCase();
        if (value.contains(UserAgentSystemEnum.ANDROID.toString().toLowerCase())) {
            return UserAgentSystemEnum.ANDROID;
        }else if (value.contains(UserAgentSystemEnum.IPHONE.toString().toLowerCase())) {
            return UserAgentSystemEnum.IPHONE;
        }
        return UserAgentSystemEnum.PC;
    }
}
